package com.dy.lock.screen.component.impl;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dy.lock.screen.component.CustomerReportComponent;
import com.dy.lock.screen.constants.TransmissionCode;
import com.dy.lock.screen.exception.ServerDisponseException;
import com.dy.lock.screen.pojo.CustomerReportInfo;
import com.dy.lock.screen.pojo.UserInfo;
import com.dy.lock.screen.scoket.Head;
import com.dy.lock.screen.service.CustomerReportService;
import com.dy.lock.screen.service.UserService;
import com.dy.lock.screen.utils.CommonUtil;
import com.dy.lock.screen.vo.CustomerReportVo;
import com.google.gson.Gson;

@Component("customerReportComponent")
public class CustomerReportComponentImpl implements CustomerReportComponent {

	private static final Logger log = Logger
			.getLogger(CustomerReportComponentImpl.class);
	private Gson gson;

	@Resource(name = "customerReportService")
	private CustomerReportService customerReportService;
	@Resource(name = "userService")
	private UserService userService;

	public CustomerReportComponentImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public boolean report(String body, Head head) {
		CustomerReportVo vo = gson.fromJson(body, CustomerReportVo.class);
		if (vo != null) {
			CustomerReportInfo info = new CustomerReportInfo();
			info.setReportCid(vo.getReportCid());
			info.setBeReportedCid(vo.getBeReportedCid());
			info.setReportReason(CommonUtil.splitToString(
					vo.getReportReasons(), ";"));
			int result = -1;
			UserInfo user = this.userService.queryByUserId(vo
					.getBeReportedCid(), head);
			if (user != null) {
				result = this.customerReportService.save(info);
			} else {
				throw new ServerDisponseException(
						TransmissionCode.REPORTED_CUSTOMER_IS_NOT_EXIST
								.getCode(),
						TransmissionCode.REPORTED_CUSTOMER_IS_NOT_EXIST
								.getMessage());
			}
			if (result > 0) {
				return true;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",用户举报操作时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}

	}

}
